//
//  HHLuminanceView.m
//  HHAVPlayer
//
//  Created by lch on 2022/1/19.
//

#import "HHLuminanceView.h"
#import <Masonry/Masonry.h>
#import <HHBlockKit/HHBlockHeader.h>
#import "HHAVPlayerHeader.h"
@interface HHLuminanceView ()

/// 亮度图标
@property (nonatomic, strong) UIImageView       *imageView;
/// 亮度
@property (nonatomic, strong) UILabel           *title;
/// 亮度小格子父视图
@property (nonatomic, strong) UIView            *luminanceItemBgView;
/// 亮度小格子
@property (nonatomic, strong) NSMutableArray    *tipArray;
// 方向改变
@property (nonatomic, assign) BOOL              orientationDidChange;

@end

@implementation HHLuminanceView

+ (instancetype)sharedLuminanceView{
    static HHLuminanceView *luminanceView;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        luminanceView = [[HHLuminanceView alloc]init];
        UIWindow *window;
     
        if (@available(iOS 13.0, *)){
            NSLog(@"connectedScenes -- %@",[UIApplication sharedApplication].connectedScenes);
            for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes) {
                if (windowScene.activationState == UISceneActivationStateForegroundActive){
                    window = windowScene.windows.firstObject;
                    break;
                }else if (windowScene.activationState == UISceneActivationStateForegroundInactive){
                    window = windowScene.windows.firstObject;
                    break;
                }
            }
        }else{
            window =  [UIApplication sharedApplication].keyWindow;
        }
        [window addSubview:luminanceView];
        
        NSLog(@"window -- %@ - %@ - %@",window,luminanceView,[UIApplication sharedApplication].keyWindow);
    });
    return luminanceView;
}


- (instancetype)init{
    if (self = [super init]) {
        [self initUI];
    }
    return self;
}
- (void)initUI{
    
    self.frame = CGRectMake(SCREENWIDTH * 0.5, SCREENHEIGHT * 0.5, 155, 155);
    self.layer.cornerRadius = 10;
    self.layer.masksToBounds = YES;
    self.alpha = 0.0;
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    //
    [self addSubview:self.title];
    [self addSubview:self.imageView];
    [self addSubview:self.luminanceItemBgView];
    // 创建音量格子
    [self createSmallBox];
    [self addNotification];
    [self addObserver];
}
#pragma mark - 创建小格子
- (void)createSmallBox{
    CGFloat boxW = (CGRectGetWidth(self.luminanceItemBgView.frame) - 17) / 16;
    CGFloat boxH = 5;
    CGFloat boxY = 1;
    
    for (int i = 0; i < 16; i++) {
        CGFloat boxX          = i * (boxW + 1) + 1;
        UIImageView *imageView    = [[UIImageView alloc] init];
        imageView.backgroundColor = [UIColor whiteColor];
        imageView.frame           = CGRectMake(boxX, boxY, boxW, boxH);
        [self.luminanceItemBgView addSubview:imageView];
        [self.tipArray addObject:imageView];
    }
    [self updateLuminanceItemBgView:[UIScreen mainScreen].brightness];
}

#pragma mark - 刷新音量格子
- (void)updateLuminanceItemBgView:(CGFloat)sound {
    CGFloat stage = 1 / 15.0;
    NSInteger level = sound / stage;
    
    for (int i = 0; i < self.tipArray.count; i++) {
        UIImageView *img = self.tipArray[i];
        if (i <= level) {
            img.hidden = NO;
        } else {
            img.hidden = YES;
        }
    }
}
#pragma makr - 通知 KVO
- (void)addNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(updateLayer:)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:nil];
}
#pragma 方向发生变化刷新layer
- (void)updateLayer:(NSNotification *)notify {
    self.orientationDidChange = YES;
    [self setNeedsLayout];
}
- (void)addObserver {
    
    [[UIScreen mainScreen] addObserver:self
                            forKeyPath:@"brightness"
                               options:NSKeyValueObservingOptionNew context:NULL];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    CGFloat sound = [change[@"new"] floatValue];
    [self appearSoundView];
    [self updateLuminanceItemBgView:sound];
}
#pragma mark - 音量框显示
- (void)appearSoundView {
    if (self.alpha == 0.0) {
        self.alpha = 1.0;
        // 3秒后自动隐藏音量框
        dispatch_after(3, dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.8 animations:^{
                self.alpha = 0.0;
            } completion:^(BOOL finished) {
                
            }];
        });
    }
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    [self setNeedsLayout];
}


- (void)layoutSubviews {
    [super layoutSubviews];
    
    if (self.orientationDidChange) {
        [UIView animateWithDuration:0.25 animations:^{
            if ([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait
                || [UIDevice currentDevice].orientation == UIDeviceOrientationFaceUp) {
                self.center = CGPointMake(SCREENWIDTH * 0.5, (SCREENHEIGHT - 10) * 0.5);
            } else {
                self.center = CGPointMake(SCREENWIDTH * 0.5, SCREENHEIGHT * 0.5);
            }
        } completion:^(BOOL finished) {
            self.orientationDidChange = NO;
        }];
    } else {
        if ([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait) {
            self.center = CGPointMake(SCREENWIDTH * 0.5, (SCREENHEIGHT - 10) * 0.5);
        } else {
            self.center = CGPointMake(SCREENWIDTH * 0.5, SCREENHEIGHT * 0.5);
            
        }
    }
    
    self.imageView.center = CGPointMake(155 * 0.5, 155 * 0.5);
}

- (void)dealloc {
    [[UIScreen mainScreen] removeObserver:self forKeyPath:@"brightness"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



#pragma mark - 懒加载
- (UILabel *)title{
    if (!_title) {
        _title = [[UILabel alloc]init];
        _title.hh_text(@"亮度")
            .hh_boldSystemFont(16)
            .hh_textColor(RGB(51, 51, 51))
            .hh_textAlignment(NSTextAlignmentCenter)
            .hh_frame(CGRectMake(0, 0, CGRectGetWidth(self.frame), 40));
        
    }
    return _title;
}
- (UIImageView *)imageView{
    if (!_imageView) {
        _imageView = [[UIImageView alloc]init];
        _imageView.hh_frame(CGRectMake((CGRectGetWidth(self.frame) - 79)/2, 40, 79, 76));
        _imageView.image = HHPlayerImageName(@"playgesture_BrightnessSun");
    }
    return _imageView;
}
- (UIView *)luminanceItemBgView{
    if (!_luminanceItemBgView) {
        _luminanceItemBgView = [[UIView alloc]initWithFrame:CGRectMake(13, 130, CGRectGetWidth(self.frame) - 26, 7)];
        _luminanceItemBgView.backgroundColor = [UIColor colorWithRed:0.25f green:0.22f blue:0.21f alpha:1.00f];
    }
    return _luminanceItemBgView;
}

- (NSMutableArray *)tipArray{
    if (!_tipArray) {
        _tipArray = [NSMutableArray arrayWithCapacity:16];
    }
    return _tipArray;
}


@end
